package emergent;

public class Monitor {

	private World world;
	private int worldPopulation = 0;
	private int notCheckedin = 0;
	private boolean sync = true;

	public synchronized void checkin(Agent agent) {
		notCheckedin--;
		if (notCheckedin > 0) {
			try {
				wait();
				return;
			} catch (InterruptedException e) {

			}
		}
		advanceTime();
		world.detect();
		notifyAll();
	}

	private void advanceTime() {
		try {
			Thread.sleep(180);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		notCheckedin = worldPopulation;
		world.setTime(world.getTime() + 1);
	}

	public World getWorld() {
		return world;
	}

	public void setWorld(World world) {
		this.world = world;
		worldPopulation = world.getNumberOfAgents();
		notCheckedin = worldPopulation;
	}

	public int getWorldPopulation() {
		return worldPopulation;
	}

	public int getNotCheckedin() {
		return notCheckedin;
	}

	public void setNotCheckedin(int notCheckedin) {
		this.notCheckedin = notCheckedin;
	}
}
